<!--
  题库详情页面
-->
<template>
  <div class="question-bank-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button
          text
          :icon="ArrowLeft"
          @click="goBack"
          class="back-btn"
        >
          返回题库列表
        </el-button>
        <h1>{{ questionBank?.name }}</h1>
        <div class="bank-meta">
          <el-tag :type="questionBank?.is_public ? 'success' : 'info'">
            {{ questionBank?.is_public ? '公开' : '私有' }}
          </el-tag>
          <span class="creator">创建者：{{ questionBank?.creator_name }}</span>
          <span class="create-time">创建时间：{{ formatDate(questionBank?.created_at) }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button
          :icon="Edit"
          @click="editQuestionBank"
          v-if="canEditBank"
        >
          编辑
        </el-button>
        <el-button
          :icon="Plus"
          type="primary"
          @click="createQuestion"
          v-if="authStore.hasPermission('question:write')"
        >
          添加题目
        </el-button>
      </div>
    </div>

    <!-- 题库统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24"><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ questionBank?.question_count || 0 }}</div>
              <div class="stat-label">题目总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon easy">
              <el-icon size="24"><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getQuestionCount('easy') }}</div>
              <div class="stat-label">简单题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon medium">
              <el-icon size="24"><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getQuestionCount('medium') }}</div>
              <div class="stat-label">中等题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon hard">
              <el-icon size="24"><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ getQuestionCount('hard') }}</div>
              <div class="stat-label">困难题目</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 题目筛选和操作 -->
    <el-card class="filter-card">
      <div class="filter-header">
        <h3>题目列表</h3>
        <div class="filter-actions">
          <el-button
            :icon="Download"
            @click="exportQuestions"
            v-if="questions.length > 0"
          >
            导出题目
          </el-button>
          <el-button
            :icon="Delete"
            @click="showBatchDeleteDialog = true"
            v-if="selectedQuestions.length > 0 && authStore.hasPermission('question:delete')"
          >
            批量删除 ({{ selectedQuestions.length }})
          </el-button>
        </div>
      </div>

      <el-form :model="filterForm" :inline="true">
        <el-form-item label="题目类型">
          <el-select
            v-model="filterForm.question_type"
            placeholder="选择类型"
            clearable
            style="width: 120px"
          >
            <el-option label="单选题" value="single_choice" />
            <el-option label="多选题" value="multiple_choice" />
            <el-option label="判断题" value="true_false" />
            <el-option label="填空题" value="fill_blank" />
            <el-option label="简答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select
            v-model="filterForm.difficulty"
            placeholder="选择难度"
            clearable
            style="width: 100px"
          >
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="filterForm.tags"
            multiple
            filterable
            placeholder="选择标签"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索题目内容"
            clearable
            style="width: 200px"
            @keyup.enter="loadQuestions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadQuestions">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题目列表 -->
    <el-card class="question-list-card">
      <div class="question-list">
        <div
          v-for="question in questions"
          :key="question.id"
          class="question-item"
          :class="{ selected: selectedQuestions.includes(question.id) }"
        >
          <div class="question-checkbox">
            <el-checkbox
              :model-value="selectedQuestions.includes(question.id)"
              @change="(checked) => toggleQuestionSelection(question.id, checked)"
            />
          </div>

          <div class="question-content" @click="viewQuestionDetail(question)">
            <div class="question-header">
              <div class="question-title">
                {{ truncateText(stripHtml(question.content), 100) }}
              </div>
              <div class="question-tags">
                <el-tag size="small" :type="getTypeTagType(question.question_type)">
                  {{ getTypeText(question.question_type) }}
                </el-tag>
                <el-tag
                  size="small"
                  :type="getDifficultyTagType(question.difficulty)"
                >
                  {{ getDifficultyText(question.difficulty) }}
                </el-tag>
                <span class="question-points">{{ question.points }}分</span>
              </div>
            </div>

            <div class="question-options" v-if="showOptions(question)">
              <div
                v-for="(option, index) in getQuestionOptions(question)"
                :key="index"
                class="option-item"
              >
                <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                <span class="option-text">{{ truncateText(option, 60) }}</span>
              </div>
            </div>

            <div class="question-meta">
              <span class="update-time">更新于 {{ formatDate(question.updated_at) }}</span>
              <div class="question-actions" @click.stop>
                <el-button
                  text
                  size="small"
                  @click="editQuestion(question)"
                  v-if="canEditQuestion(question)"
                >
                  编辑
                </el-button>
                <el-button
                  text
                  size="small"
                  type="danger"
                  @click="deleteQuestion(question)"
                  v-if="canDeleteQuestion(question)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && questions.length === 0" class="empty-state">
          <el-empty description="暂无题目">
            <el-button
              type="primary"
              @click="createQuestion"
              v-if="authStore.hasPermission('question:write')"
            >
              添加第一道题目
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadQuestions"
          @current-change="loadQuestions"
        />
      </div>
    </el-card>

    <!-- 批量删除确认对话框 -->
    <el-dialog
      v-model="showBatchDeleteDialog"
      title="批量删除确认"
      width="400px"
    >
      <p>确定要删除选中的 {{ selectedQuestions.length }} 道题目吗？此操作不可恢复！</p>
      <template #footer>
        <el-button @click="showBatchDeleteDialog = false">取消</el-button>
        <el-button
          type="danger"
          :loading="batchDeleteLoading"
          @click="confirmBatchDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores'
import {
  getQuestionBank,
  getQuestions,
  deleteQuestion as apiDeleteQuestion,
  batchDeleteQuestions
} from '@/api/questions'
import type { QuestionBank, Question } from '@/types'
import {
  ArrowLeft,
  Edit,
  Plus,
  Document,
  Star,
  Download,
  Delete
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const bankId = Number(route.params.id)

// 响应式数据
const loading = ref(false)
const questionBank = ref<QuestionBank | null>(null)
const questions = ref<Question[]>([])
const selectedQuestions = ref<number[]>([])
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  question_type: '',
  difficulty: '',
  tags: [] as string[],
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  page_size: 20
})

// 批量操作
const showBatchDeleteDialog = ref(false)
const batchDeleteLoading = ref(false)

// 可用标签
const availableTags = computed(() => {
  const allTags = new Set<string>()
  questions.value.forEach(q => {
    q.tags?.forEach(tag => allTags.add(tag))
  })
  return Array.from(allTags)
})

// 加载题库信息
const loadQuestionBankInfo = async () => {
  try {
    const response = await getQuestionBank(bankId)
    questionBank.value = response.data
  } catch (error) {
    console.error('Failed to load question bank:', error)
    ElMessage.error('加载题库信息失败')
  }
}

// 加载题目列表
const loadQuestions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.page_size,
      question_bank: bankId,
      question_type: filterForm.question_type || undefined,
      difficulty: filterForm.difficulty || undefined,
      tags: filterForm.tags.length > 0 ? filterForm.tags : undefined,
      search: filterForm.keyword || undefined
    }

    const response = await getQuestions(params)
    questions.value = response.data.results
    total.value = response.data.count
  } catch (error) {
    console.error('Failed to load questions:', error)
    ElMessage.error('加载题目失败')
  } finally {
    loading.value = false
  }
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    question_type: '',
    difficulty: '',
    tags: [],
    keyword: ''
  })
  pagination.page = 1
  loadQuestions()
}

// 返回题库列表
const goBack = () => {
  router.push('/questions/banks')
}

// 编辑题库
const editQuestionBank = () => {
  // TODO: 实现编辑题库功能
  ElMessage.info('编辑题库功能开发中...')
}

// 创建题目
const createQuestion = () => {
  router.push({
    name: 'QuestionCreate',
    query: { bank_id: bankId }
  })
}

// 查看题目详情
const viewQuestionDetail = (question: Question) => {
  router.push(`/questions/questions/${question.id}`)
}

// 编辑题目
const editQuestion = (question: Question) => {
  router.push(`/questions/questions/${question.id}/edit`)
}

// 删除题目
const deleteQuestion = async (question: Question) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除题目 "${truncateText(stripHtml(question.content), 30)}..." 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await apiDeleteQuestion(question.id)
    ElMessage.success('题目删除成功')
    loadQuestions()
    loadQuestionBankInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete question:', error)
      ElMessage.error('删除题目失败')
    }
  }
}

// 切换题目选择
const toggleQuestionSelection = (questionId: number, checked: boolean) => {
  if (checked) {
    selectedQuestions.value.push(questionId)
  } else {
    const index = selectedQuestions.value.indexOf(questionId)
    if (index > -1) {
      selectedQuestions.value.splice(index, 1)
    }
  }
}

// 确认批量删除
const confirmBatchDelete = async () => {
  batchDeleteLoading.value = true
  try {
    await batchDeleteQuestions({ question_ids: selectedQuestions.value })
    ElMessage.success(`成功删除 ${selectedQuestions.value.length} 道题目`)
    selectedQuestions.value = []
    showBatchDeleteDialog.value = false
    loadQuestions()
    loadQuestionBankInfo()
  } catch (error) {
    console.error('Failed to batch delete questions:', error)
    ElMessage.error('批量删除失败')
  } finally {
    batchDeleteLoading.value = false
  }
}

// 导出题目
const exportQuestions = () => {
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中...')
}

// 权限检查
const canEditBank = computed(() => {
  return questionBank.value && (
    questionBank.value.creator === authStore.user?.id ||
    authStore.hasRole('admin')
  )
})

const canEditQuestion = (question: Question) => {
  return authStore.hasPermission('question:write') &&
         (question.creator === authStore.user?.id || authStore.hasRole('admin'))
}

const canDeleteQuestion = (question: Question) => {
  return authStore.hasPermission('question:delete') &&
         (question.creator === authStore.user?.id || authStore.hasRole('admin'))
}

// 工具函数
const formatDate = (dateString?: string) => {
  return dateString ? new Date(dateString).toLocaleDateString() : ''
}

const stripHtml = (html: string) => {
  return html.replace(/<[^>]*>/g, '')
}

const truncateText = (text: string, maxLength: number) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const getTypeText = (type: string) => {
  const types: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    essay: '简答题'
  }
  return types[type] || type
}

const getTypeTagType = (type: string) => {
  const types: Record<string, string> = {
    single_choice: 'primary',
    multiple_choice: 'success',
    true_false: 'warning',
    fill_blank: 'info',
    essay: 'danger'
  }
  return types[type] || 'info'
}

const getDifficultyText = (difficulty: string) => {
  const difficulties: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficulties[difficulty] || difficulty
}

const getDifficultyTagType = (difficulty: string) => {
  const types: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

const getQuestionCount = (difficulty: string) => {
  if (!questionBank.value?.difficulty_distribution) return 0
  return questionBank.value.difficulty_distribution[difficulty] || 0
}

const showOptions = (question: Question) => {
  return ['single_choice', 'multiple_choice'].includes(question.question_type)
}

const getQuestionOptions = (question: Question) => {
  if (question.options && Array.isArray(question.options)) {
    return question.options
  }
  return []
}

// 页面挂载时加载数据
onMounted(() => {
  loadQuestionBankInfo()
  loadQuestions()
})
</script>

<style scoped lang="scss">
.question-bank-detail {
  .page-header {
    margin-bottom: 24px;

    .back-btn {
      margin-bottom: 12px;
    }

    h1 {
      font-size: 28px;
      color: var(--el-text-color-primary);
      margin: 0 0 12px 0;
    }

    .bank-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      font-size: 14px;
      color: var(--el-text-color-regular);

      .creator,
      .create-time {
        color: var(--el-text-color-placeholder);
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
      margin-top: 16px;
    }
  }

  .stats-row {
    margin-bottom: 24px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);

          &.easy {
            background: var(--el-color-success-light-9);
            color: var(--el-color-success);
          }

          &.medium {
            background: var(--el-color-warning-light-9);
            color: var(--el-color-warning);
          }

          &.hard {
            background: var(--el-color-danger-light-9);
            color: var(--el-color-danger);
          }
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-regular);
          }
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 24px;

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        font-size: 18px;
        color: var(--el-text-color-primary);
        margin: 0;
      }

      .filter-actions {
        display: flex;
        gap: 8px;
      }
    }
  }

  .question-list-card {
    .question-list {
      .question-item {
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        margin-bottom: 16px;
        overflow: hidden;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        &.selected {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }

        .question-checkbox {
          padding: 16px;
          border-right: 1px solid var(--el-border-color-lighter);
        }

        .question-content {
          flex: 1;
          padding: 16px;
          cursor: pointer;

          .question-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;

            .question-title {
              flex: 1;
              font-size: 16px;
              color: var(--el-text-color-primary);
              line-height: 1.5;
            }

            .question-tags {
              display: flex;
              align-items: center;
              gap: 8px;
              flex-shrink: 0;

              .question-points {
                font-size: 12px;
                color: var(--el-text-color-regular);
                background: var(--el-fill-color-light);
                padding: 2px 6px;
                border-radius: 4px;
              }
            }
          }

          .question-options {
            margin-bottom: 12px;

            .option-item {
              display: flex;
              align-items: flex-start;
              margin-bottom: 6px;
              font-size: 14px;
              color: var(--el-text-color-regular);

              .option-label {
                color: var(--el-text-color-primary);
                font-weight: 500;
                margin-right: 8px;
                flex-shrink: 0;
              }

              .option-text {
                flex: 1;
              }
            }
          }

          .question-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: var(--el-text-color-placeholder);

            .question-actions {
              display: flex;
              gap: 8px;
              opacity: 0;
              transition: opacity 0.3s;
            }
          }

          &:hover .question-actions {
            opacity: 1;
          }
        }
      }

      .loading-container {
        padding: 20px;
      }

      .empty-state {
        padding: 60px 20px;
        text-align: center;
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .question-bank-detail {
    .page-header {
      .bank-meta {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
      }

      .header-right {
        flex-direction: column;
      }
    }

    .stats-row {
      .stat-card .stat-content {
        .stat-icon {
          width: 40px;
          height: 40px;
        }

        .stat-info .stat-value {
          font-size: 20px;
        }
      }
    }

    .filter-card {
      .filter-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;

        .filter-actions {
          justify-content: flex-start;
        }
      }
    }

    .question-list-card {
      .question-list {
        .question-item {
          .question-content {
            .question-header {
              flex-direction: column;
              gap: 8px;

              .question-tags {
                align-self: flex-start;
              }
            }

            .question-meta {
              flex-direction: column;
              align-items: flex-start;
              gap: 8px;

              .question-actions {
                opacity: 1;
              }
            }
          }
        }
      }
    }
  }
}
</style>